#include "covMatrix.h"
#include "JacbiCor.h"

// 计算输入数据的协方差矩阵
// 特征值分解后，降维
// test_covMatrix infile  outfile columns 
// test_covMatrix cov.txt result  20      
// infile：输入原始数据文件
// columns：原始数据列数，协方差方陈大小
// outfile：输出协方差矩阵，特征值，特征向量
// gcc -Wall -g -O2 -o test_covMatrix test_covMatrix.c covMatrix.c JacbiCor.c -lm

int main(int argc, char* argv[])
{ char *inFileName=argv[1];
  FILE *infile=fopen(inFileName,"rt");
  char *outFileName=argv[2];
  FILE *outfile=fopen(outFileName,"wt");
   
  int  n=atoi(argv[3]);

  double *s2=malloc(n*n*sizeof(double));
  memset(s2,0,n*n*sizeof(double));
  c_covMatrix(infile, n, s2);
 
  //输出协方差矩阵  
  fprintf(outfile,"covariance matrix\n");
  for (int i=0; i<n; i++)
  {    for (int j=0; j<n-1; j++)
      fprintf(outfile," %f,",s2[i*n + j]);
    fprintf(outfile," %f\n",s2[i*n + n-1]);
  }
  
  double *eigenValues=malloc(n*sizeof(double));
  double *vectors=malloc(n*n*sizeof(double));
  JacbiCor(s2, n, vectors, eigenValues, 1e-10, n*n);
    
  fprintf(outfile,"\neigenValues\n");
  for (int i=0; i<n; i++)
    fprintf(outfile," %f,",eigenValues[i]); 
  fprintf(outfile,"\n"); 
	  
  fprintf(outfile,"\nVectors\n");
  for (int i=0; i<n; i++)
  { for (int j=0; j<n-1; j++)
      fprintf(outfile," %f,",vectors[i*n+j]);
    fprintf(outfile," %f\n",vectors[i*n+n-1]);
  }
    
  free(s2);
  free(eigenValues);
  free(vectors);

  fclose(infile);
  fclose(outfile);
  return 0;
}
